// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// s [author] rhyme_lph
// z [email]  rhymelph@gmail.com
// B [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/payslips_item_entity.dart';
import 'package:finance_app/src/http_service/http_payslips_service.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/provider/dashboard_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/payroll_provider.dart';
import 'package:finance_app/src/router_gen/override_route_providers.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';

class PayrollDeleteProvider extends BaseProvider<List<PayslipsItemEntity>>
    with SearchDataListMixin, FormatGroupMapLocalMixin<PayslipsItemEntity> {
  List<PayslipsItemEntity> currentSelectList = [];

  @override
  Future get dataFuture => HttpPayslipsService.payslipsList('unpaid');

  void onDelete() async {
    if (currentSelectList.length == 0) {
      return;
    }
    List<int> ids = currentSelectList.map((e) => e.id).toList();

    obtainContext?.call((context) async {
      final isSuccess = await showDeletePayslipsBottomSheet(context);
      if (isSuccess == true) {
        bool isSuccess = false;
        await post(HttpPayslipsService.payslipsBatchDelete(ids),
            autoHandler: AutoHandler.Toast,
            loadingTip: 'Loading', onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess == true) {
          await showPayslipsDeleteSuccessBottomSheet(context);
          data.removeWhere((element) => ids.contains(element.id));
          data = transformData(data, false);
          currentSelectList.clear();
          update();
          Providers.get<HrAndPayrollProvider>(
                  RouterGenProviders.hrAndPayrollPage, null)
              ?.getChildProvider<PayrollProvider>()
              ?.batchDelete(ids);
          if (!Config.hasPermission(PermissionUtils.homeDashboard))
            Config.dashboardProvider
                ?.getChildProvider<HrAndPayrollProvider>()
                ?.getChildProvider<PayrollProvider>()
                ?.batchDelete(ids);
          Navigator.of(context).pop();
        }
      }
    });
  }

  void onCancel() {
    obtainContext?.call((context) {
      Navigator.of(context).pop();
    });
  }

  void onSelect(PayslipsItemEntity item1) {
    if (currentSelectList.contains(item1)) {
      currentSelectList.remove(item1);
    } else {
      currentSelectList.add(item1);
    }
    update();
  }

  @override
  FutureOr<List<PayslipsItemEntity>> transformData(
      List<PayslipsItemEntity> d, bool isCache) {
    groupMap.clear();
    contactToMap(d);
    return super.transformData(d, isCache);
  }

  @override
  void searchRefreshData(searchData) {
    transformData(data, false);
    update();
  }

  void contactToMap(List<PayslipsItemEntity> list) {
    sortGroupToMap(list,
        sort: (a, b) => sortIssuesAt(a, b, (t) => t.startDate, (t) => t.id),
        filter: (a) =>
            onFilterSearch(searchController.text, a.name) ||
            onFilterSearch(searchController.text, a.number),
        group: (a) => groupMonth(a, (t) => t.startDate));
  }
}
